package com.hsd.netty.client.strategy;

import com.hsd.netty.client.common.NettyHeader;
import com.hsd.netty.client.common.NettyMessage;
import com.hsd.netty.client.constants.NettyClientConstants;
import com.hsd.netty.client.enums.MessageCode;
import com.hsd.netty.client.task.HeartBeatTask;
import com.hsd.netty.client.cache.OverallStaticCache;
import io.netty.channel.ChannelHandlerContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.TimeUnit;

/**
 * @author s.he
 * on 2020/6/6
 */
public class LoginStrategy extends NettyMessageAdapter {
    private static final Logger logger = LoggerFactory.getLogger(LoginStrategy.class);


    @Override
    public void handleServerResponse(ChannelHandlerContext ctx, Object msg) {
        NettyMessage nettyMessage = (NettyMessage) msg;
        NettyHeader nettyHeader = nettyMessage.getNettyHeader();
        if(nettyHeader.getStatusCode().equals(MessageCode.SUCCESS.getCode())) {
            logger.info("【登录成功】，返回的sessionId为:" + nettyHeader.getSessionId());
            OverallStaticCache.loginInfoMap.put(NettyClientConstants.CHANNEL_CONTEXT, ctx);
            OverallStaticCache.setSessionId(String.valueOf(nettyHeader.getSessionId()));
            String isHeartBeat = OverallStaticCache.getHeartBeat();
            if(StringUtils.isBlank(isHeartBeat) || StringUtils.equalsIgnoreCase(isHeartBeat, NettyClientConstants.FALSE)) {
                ctx.executor().scheduleAtFixedRate(new HeartBeatTask(ctx), 0, 5, TimeUnit.SECONDS);
            }
        } else {
            logger.error("登录失败，返回的错误代码为:" + nettyHeader.getStatusCode());
        }
    }
}
